import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {SettingProvider} from "../../../providers/me/setting/setting.provider";
import {LoadingService} from "../../../services/common/loading.service";
import {ToastService} from "../../../services/common/toast.service";


@IonicPage()
@Component({
    selector: 'page-nick-name-setting',
    templateUrl: 'nick-name-setting.html',
    providers: [
        SettingProvider,
        ToastService,
        LoadingService
    ]
})
export class NickNameSettingPage {

    public nickName: string = '';
    private nameReg: RegExp = /^[a-zA-Z\u4e00-\u9fa5\\u0020\s]{1,15}$/;
    constructor(public navCtrl: NavController, public navParams: NavParams,
                private loadingService: LoadingService,
                private toastService: ToastService,
                private settingProvider: SettingProvider) {
    }


    ionViewDidLoad() {
        this.nickName=this.navParams.get('nickName');
    }

    saveNickName() {

        let nickName= this.nickName.trim();
        if(!nickName){
            this.toastService.showToast("请输入昵称");
            return;
        }

        if(!this.validateName(nickName)){
            return;
        }
        this.loadingService.showLoading();
        let nickNameObj= {'nickName': nickName};
        this.settingProvider.saveNickName(nickNameObj).subscribe(()=>{
            localStorage.setItem('nickName', nickName);
            this.loadingService.dismissLoading();
            this.navCtrl.pop();
        },(error) => {
            this.loadingService.dismissLoading();
            if(error.status==500){
                this.toastService.showToast('昵称修改失败');
            }
        });
    }


    private validateName(userName){
        if (userName.length > 0 && !this.nameReg.test(userName)) {
            this.toastService.showToast("昵称只能输入中英文字符");
            return false;
        }
        return true;
    }

    inputBlur(){
        let userName=this.nickName;
        this.validateName(userName);
    }

    backHandle() {
        this.navCtrl.pop();
    }
}
